package com.mathdroid.gui.main.browser;

import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.LinkedList;

import javax.swing.ToolTipManager;

import com.mathdroid.gui.main.character.ItemSlotPopup;
import com.mathdroid.model.Model;
import com.mathdroid.model.enums.EItemSlot;
import com.mathdroid.model.items.Item;

/**
 * This mouse listener listens to mouse clicks in the item browser panel.
 * It only reacts to clicks on icon areas.
 */
public final class BrowserMouseListener implements MouseListener {
	
	/**
	 * The areas that respond to mouse events.
	 */
	private LinkedList<Rectangle> iconArea = new LinkedList<Rectangle>();
	
	/**
	 * The items that are shown in the panel.
	 */
	private LinkedList<Item> shownItems = new LinkedList<Item>();
	
	/**
	 * The parent ItemSlotPopup. This can be null, if the parent is no PopUp.
	 */
	private ItemSlotPopup popup = null;
	
	/**
	 * The horizontal offset of the "Star" icon relative to the left side of
	 * the rating bar.
	 */
	private static final int STAR_OFFSET = 30;
	
	/**
	 * The item slot to put the item in, if "popup" is not null.
	 */
	private EItemSlot slot = null;
	
	/**
	 * Create a new mouse listener.
	 * @param areas The clickable areas.
	 * @param items The list of items that are associated with the areas.
	 * @param p The parent component. Can be null.
	 * @param s The slot to put the module in, if popup is not null.
	 */
	public BrowserMouseListener(final LinkedList<Rectangle> areas, 
			final LinkedList<Item> items, final ItemSlotPopup p, 
			final EItemSlot s) {
		this.iconArea = areas;
		this.shownItems = items;
		this.popup = p;
		this.slot = s;
	}

	@Override
	public void mouseClicked(final MouseEvent e) {
		final int x = e.getX();
		final int y = e.getY();
		int i = 0;
		
		for (Rectangle r : this.iconArea) {
			if (x > r.getX() && x < r.getX() + r.getWidth()
					&& y > r.getY() && y < r.getY() + r.getHeight()) {
				Item item = this.shownItems.get(i);
				new BrowserContextMenu(item, e, this.popup, this.slot);
			}
			if (x > r.getX() + STAR_OFFSET 
					&& x < r.getX() + STAR_OFFSET + r.getWidth()
					&& y > r.getY() && y < r.getY() + r.getHeight()) {
				Item item = this.shownItems.get(i);
				if (item.isAvailable()) {
					item.setAvailable(false);
				} else {
					item.setAvailable(true);
				}
				Model.refreshItemBrowserModel();
			}
			i++;
		}
	}

	@Override
	public void mouseEntered(final MouseEvent e) { }

	@Override
	public void mouseExited(final MouseEvent e) {
		ToolTipManager.sharedInstance().setEnabled(true);
	}

	@Override
	public void mousePressed(final MouseEvent arg0) { }

	@Override
	public void mouseReleased(final MouseEvent arg0) { }

}
